package com.sunday.volunteer.fragment.tab;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sunday.common.model.ResultDO;
import com.sunday.common.qrcode.CaptureActivity;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.member.alipay.Base64;
import com.sunday.member.base.BaseFragment;
import com.sunday.volunteer.BaseApp;
import com.sunday.volunteer.R;
import com.sunday.volunteer.adapter.IndexAdapter;
import com.sunday.volunteer.entity.Activity;
import com.sunday.volunteer.entity.Images;
import com.sunday.volunteer.entity.Member;
import com.sunday.volunteer.entity.Product;
import com.sunday.volunteer.http.HttpClient;
import com.sunday.volunteer.ui.MainActivity;
import com.sunday.volunteer.ui.user.RakingActivity;
import com.sunday.volunteer.utils.BaseUtil;
import com.sunday.volunteer.utils.CallActivity;
import com.sunday.volunteer.utils.CallFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.http.Field;

/**
 * Created by Pual's PC on 2016/10/8.
 */
public class IndexFragment extends CallFragment {

    @Bind(R.id.swipfresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.call)
    TextView call;

    private LinearLayoutManager layoutManager;
    private IndexAdapter adapter;
    private SparseArray sparseArray;

    private String sortField  = null;
    private String sortOrder = null;
    private int pageNo = 1;
    private List<Activity> list = new ArrayList<>();

    private boolean ishours = false;
    private int tab02 = 0;
    private int tab03 = 0;
    private int tabs = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_index, null);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        sparseArray = new SparseArray();

        adapter = new IndexAdapter(sparseArray, new int[]{R.layout.index_header, R.layout.index_item});
        adapter.setOnClickListener(onClickListener);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        swipeRefreshLayout.setColorSchemeResources(R.color.material_red, R.color.material_green,
                R.color.material_blue, R.color.material_yellow);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        recyclerView.setAdapter(adapter);

        getData();
        handlerRecyclerView();
    }

    @OnClick(R.id.left_img)
    void leftImg() {
        ((MainActivity) getActivity()).setPager(1);
    }

    @OnClick(R.id.title_msg)
    void titleMsg() {
        ToastUtils.showToast(mContext, "titlemsg");
    }

    @OnClick(R.id.title_scan)
    void titleScan() {
        check();
    }

    @OnClick(R.id.call)
    void call() {
        toCall("18968173081");
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.item:
                    long id = (long) view.getTag();
                    BaseUtil.openActivityDetialActivity(mContext, id);
                    break;
                case R.id.to_raking:
                    BaseUtil.openActivity(mContext , RakingActivity.class);
                    break;
                case R.id.tab01:
                    tab03 = 0;
                    ishours = false;
                    sortField = null;
                    sortOrder = null;
                    pageNo = 1;
                    getData();
                    tabs = 0;
                    updateTabs();
                    break;
                case R.id.tab02:

                    break;
                case R.id.tab03:
                    ishours = true;
                    if(ishours){
                        if(TextUtils.isEmpty(sortOrder)){
                            sortOrder = "DESC";
                            tab03 = 1;
                        }else {
                            sortOrder = null;
                            tab03 = 2;
                        }
                    }

                    sortField = "hours";
                    pageNo = 1;
                    tabs = 2;
                    getData();
                    updateTabs();
                    break;
            }
        }
    };

    private void updateTabs(){
        adapter.getTab01().setChecked(false);
        adapter.getTab02().setChecked(false);
        adapter.getTab03().setChecked(false);
        switch (tabs){
            case 0:
                adapter.getTab01().setChecked(true);
                break;
            case 1:
                adapter.getTab02().setChecked(true);
                break;
            case 2:
                adapter.getTab03().setChecked(true);
                break;
        }
        Drawable drawable = null;
        switch (tab02){
            case 0:
                drawable = mContext.getResources().getDrawable(R.mipmap.sort_hours_normal);
                break;
            case 1:
                drawable = mContext.getResources().getDrawable(R.mipmap.sort_hours_sel_up);
                break;
            case 2:
                drawable = mContext.getResources().getDrawable(R.mipmap.sort_hours_sel_down);
                break;
        }
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        adapter.getTab02().setCompoundDrawables(null, null, drawable, null);
        switch (tab03){
            case 0:
                drawable = mContext.getResources().getDrawable(R.mipmap.sort_hours_normal);
                break;
            case 1:
                drawable = mContext.getResources().getDrawable(R.mipmap.sort_hours_sel_down);
                break;
            case 2:
                drawable = mContext.getResources().getDrawable(R.mipmap.sort_hours_sel_up);
                break;
        }
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        adapter.getTab03().setCompoundDrawables(null, null, drawable, null);

    }

    private int lastVisibleItem;
    private boolean isCanloadMore = false;

    private void handlerRecyclerView() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;
                sparseArray.clear();
                getData();
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    pageNo ++;
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                isCanloadMore = dy>0?true:false;
                call.setVisibility(dy > 0 ? View.GONE : View.VISIBLE);
            }
        });


    }


    private void getData() {
        Call<ResultDO<List<Activity>>> call = HttpClient.getHttpAdapter().getActivitys(BaseApp.getInstance().getMemberId(), pageNo, 20,sortField ,sortOrder ,null);
        call.enqueue(new Callback<ResultDO<List<Activity>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Activity>>> call, Response<ResultDO<List<Activity>>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                swipeRefreshLayout.setRefreshing(false);
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    if(pageNo == 1){
                        list.clear();
                    }
                    list.addAll(response.body().getResult());
                    sparseArray.put(1, list);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Activity>>> call, Throwable t) {
                swipeRefreshLayout.setRefreshing(false);
            }
        });

        Call<ResultDO<List<Images>>> call2 = HttpClient.getHttpAdapter().getNews("3");
        call2.enqueue(new Callback<ResultDO<List<Images>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Images>>> call, Response<ResultDO<List<Images>>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                swipeRefreshLayout.setRefreshing(false);
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    sparseArray.put(0, response.body().getResult());
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Images>>> call, Throwable t) {
                swipeRefreshLayout.setRefreshing(false);
            }
        });

    }

    public void setData(Member member) {
        adapter.getHours().setText(String.format("%d", member.getHours()));
        adapter.getRanking().setText(String.format("%s", member.getMingci()));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1111 && resultCode == getActivity().RESULT_OK) {
            String result = data.getStringExtra("result");
            if (TextUtils.isEmpty(result)) {
                ToastUtils.showToast(mContext, "二维码不合法");
                return;
            }
            Gson gson = new Gson();
            HashMap<String, String> map = new HashMap<>();
            try {
                map = gson.fromJson(result, new TypeToken<HashMap<String, String>>() {
                }.getType());
            } catch (Exception e) {
                ToastUtils.showToast(mContext, "二维码不合法");
            }
            String id = map.get("activityId");

            Sign(id);
            //ToastUtils.showToast(mContext, id + "");

        }
    }

    private void Sign(String id) {
        Call<ResultDO> call = HttpClient.getHttpAdapter().sign(BaseApp.getInstance().getMemberId(), id);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if(response.body() == null || isFinish){
                    return;
                }
                if(response.body().getCode() == 0){
                    ToastUtils.showToast(mContext , response.body().getMessage());
                }else {
                    ToastUtils.showToast(mContext , response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {

            }
        });
    }

    private void check() {
        PackageManager pkgManager = getActivity().getPackageManager();
//        boolean sdCardReadPermission =
//                pkgManager.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;
//        // read phone state用于获取 imei 设备信息
//        boolean phoneSatePermission =
//                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        //相机权限
        boolean cameraPermission =
                pkgManager.checkPermission(Manifest.permission.CAMERA, getActivity().getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (!cameraPermission) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA},
                    0);
        } else {
            // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
            //PushManager.getInstance().initialize(this.getApplicationContext());
            intent = new Intent(mContext, CaptureActivity.class);
            startActivityForResult(intent, 1111);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 0:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
                    //PushManager.getInstance().initialize(this.getApplicationContext());
                    intent = new Intent(mContext, CaptureActivity.class);
                    startActivityForResult(intent, 1111);
                } else {
                    //checkMMS();
                    show();
                }
                return;
        }
    }

    private void show() {
        final UIAlertView view = new UIAlertView(mContext, "温馨提示", "权限已被关闭，是否需要重新设置", "取消", "确定");
        view.setClicklistener(new UIAlertView.ClickListenerInterface() {
            @Override
            public void doLeft() {
                view.dismiss();
            }

            @Override
            public void doRight() {
                view.dismiss();
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        view.show();
    }


}
